package com.lhl.forum.controller;

import com.lhl.forum.common.AppResult;
import com.lhl.forum.common.ResultCode;
import com.lhl.forum.exception.ApplicationException;
import com.lhl.forum.model.Board;
import com.lhl.forum.service.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Api(tags = "版块接口")
@RestController
@RequestMapping("/board")
public class BoardController {

    @Value("${lhl-forum.index.board-num: 9}")
    private Integer indexBoardNum;

    @Resource
    private IBoardService boardService;

    /**
     * 获取首页版块列表
     * @return
     */
    @ApiOperation("查询版块列表")
    @PostMapping("/topList")
    public AppResult<List<Board>> topList(){
        //首个版块列表的数量
        log.info("首个版块列表的数量为：" + indexBoardNum);

        //调用service层进行查询
        List<Board> boards = boardService.selectByNum(indexBoardNum);

        //非空判断
        if (boards == null) {
          boards = new ArrayList<>();
        }


        return AppResult.success(boards);
    }

    /**
     * 根据版块ID获取版块信息
     * @param id 版块id
     * @return
     */
    @ApiOperation("获取版块信息")
    @GetMapping("/getById")
    public AppResult<Board> getById(@ApiParam("版块id") @RequestParam("id") @NonNull Long id){
        //调用service
        Board board = boardService.selectById(id);
        //判断版块是否存在
        if (board == null || board.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        return AppResult.success(board);

    }
}
